<template>
  <div class="min-h-screen bg-gray-100">
    <header class="bg-white shadow">
      <div class="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex items-center">
        <button 
          @click="router.push('/')" 
          class="mr-3 text-gray-500 hover:text-gray-700 focus:outline-none"
          title="返回聊天"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
        </button>
        <h1 class="text-xl font-semibold text-gray-900">个人资料</h1>
      </div>
    </header>

    <main class="max-w-2xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div v-if="loading" class="text-center py-12">
        <div class="text-gray-500">加载中...</div>
      </div>

      <div v-else-if="error" class="text-center py-12">
        <div class="text-red-500">{{ error }}</div>
        <button @click="fetchProfile" class="mt-4 btn btn-primary">重试</button>
      </div>

      <template v-else>
        <!-- 查看模式 -->
        <div v-if="!isEditing" class="bg-white shadow rounded-lg overflow-hidden">
          <!-- 头像区域 -->
          <div class="bg-gradient-to-r from-blue-100 to-primary p-6 flex justify-center">
            <div class="relative">
              <div class="h-28 w-28 rounded-full bg-white p-1 shadow-md cursor-pointer" @click="enableEditing">
                <div v-if="profile.avatar && !profile.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-cover bg-center" :style="`background-image: url('${fullProfileAvatarUrl}')`"></div>
                <div v-else-if="profile.avatar && profile.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-gray-100 flex items-center justify-center">
                  <span class="text-5xl">{{ profile.avatar.replace('emoji:', '') }}</span>
                </div>
                <div v-else class="h-full w-full rounded-full bg-gray-300 flex items-center justify-center text-2xl font-bold text-gray-700">
                  {{ profile.username ? profile.username[0].toUpperCase() : '?' }}
                </div>
              </div>
              <div class="absolute -bottom-1 -right-1 h-5 w-5 rounded-full" :class="profile.status === 'online' ? 'bg-green-500' : 'bg-gray-400'"></div>
            </div>
          </div>

          <!-- 个人信息 -->
          <div class="p-6">
            <h2 class="text-xl font-bold text-center mb-6">{{ profile.username }}</h2>
            <div class="space-y-4">
              <div class="flex border-b border-gray-100 pb-3">
                <span class="w-1/3 text-gray-500">邮箱</span>
                <span class="w-2/3 font-medium">{{ profile.email }}</span>
              </div>
              <div class="flex border-b border-gray-100 pb-3">
                <span class="w-1/3 text-gray-500">个人简介</span>
                <span class="w-2/3 font-medium">{{ profile.bio || '暂无' }}</span>
              </div>
              <div class="flex border-b border-gray-100 pb-3">
                <span class="w-1/3 text-gray-500">位置</span>
                <span class="w-2/3 font-medium">{{ profile.location || '暂无' }}</span>
              </div>
              <div class="flex">
                <span class="w-1/3 text-gray-500">生日</span>
                <span class="w-2/3 font-medium">{{ profile.birthday ? formatDate(profile.birthday) : '暂无' }}</span>
              </div>
            </div>

            <div class="mt-6">
              <button 
                @click="enableEditing" 
                class="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-blue-700 focus:outline-none"
              >
                编辑资料
              </button>
            </div>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="bg-white shadow rounded-lg overflow-hidden">
          <div class="bg-gradient-to-r from-blue-100 to-primary p-6 flex justify-center">
            <div class="relative">
              <div class="h-28 w-28 rounded-full bg-white p-1 shadow-md overflow-hidden">
                <div v-if="formData.avatar && !formData.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-cover bg-center" :style="`background-image: url('${previewAvatar || fullAvatarUrl}')`"></div>
                <div v-else-if="formData.avatar && formData.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-gray-100 flex items-center justify-center">
                  <span class="text-5xl">{{ formData.avatar.replace('emoji:', '') }}</span>
                </div>
                <div v-else class="h-full w-full rounded-full bg-gray-300 flex items-center justify-center text-2xl font-bold text-gray-700">
                  {{ formData.username ? formData.username[0].toUpperCase() : '?' }}
                </div>

                <!-- 头像上传按钮 -->
                <div class="absolute inset-0 bg-black bg-opacity-40 opacity-0 hover:opacity-100 flex items-center justify-center transition-opacity cursor-pointer" @click="triggerFileInput">
                  <span class="text-white text-xs font-medium">更换头像</span>
                </div>
                <input 
                  ref="fileInput" 
                  type="file" 
                  accept="image/*" 
                  @change="handleFileChange" 
                  class="hidden"
                >
              </div>
            </div>
          </div>

          <!-- 表单区域 -->
          <form @submit.prevent="updateProfile" class="p-6">
            <!-- 头像选择区域 -->
            <div class="mb-6 border p-4 rounded-lg bg-white shadow-sm">
              <h2 class="text-base font-medium text-gray-700 mb-4 border-b pb-2">更换头像</h2>
              
              <!-- 头像预览 -->
              <div class="mb-6 flex justify-center">
                <div class="w-28 h-28 relative">
                  <div class="w-full h-full rounded-full overflow-hidden border-2 border-gray-200 shadow-sm">
                    <div v-if="formData.avatar && !formData.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-cover bg-center" :style="`background-image: url('${previewAvatar || fullAvatarUrl}')`"></div>
                    <div v-else-if="formData.avatar && formData.avatar.startsWith('emoji:')" class="h-full w-full rounded-full bg-gray-100 flex items-center justify-center">
                      <span class="text-5xl">{{ formData.avatar.replace('emoji:', '') }}</span>
                    </div>
                    <div v-else class="h-full w-full rounded-full bg-gray-300 flex items-center justify-center text-2xl font-bold text-gray-700">
                      {{ formData.username ? formData.username[0].toUpperCase() : '?' }}
                    </div>
                  </div>
                  
                  <!-- 悬浮提示 -->
                  <div class="absolute -bottom-1 -right-1 bg-gray-100 py-1 px-2 rounded-full text-xs text-gray-500 shadow-sm border border-gray-200">
                    {{ formData.avatar?.startsWith('emoji:') ? 'Emoji' : '图片' }}
                  </div>
                </div>
              </div>
              
              <!-- 上传头像区域 -->
              <div class="grid grid-cols-2 gap-3 mb-4">
                <!-- 上传头像按钮 -->
                <button 
                  type="button"
                  @click="triggerFileInput" 
                  class="flex items-center justify-center px-3 py-3 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 border border-gray-300 text-sm transition-colors"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                  选择图片头像
                </button>
                <input 
                  ref="fileInput" 
                  type="file" 
                  accept="image/*" 
                  @change="handleFileChange" 
                  class="hidden"
                />
                
                <!-- 清除头像按钮 -->
                <button 
                  type="button"
                  @click="clearAvatar" 
                  class="flex items-center justify-center px-3 py-3 bg-red-50 text-red-600 rounded-md hover:bg-red-100 border border-red-200 text-sm transition-colors"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  清除头像
                </button>
              </div>
              
              <!-- 或分隔线 -->
              <div class="relative flex py-3 items-center mb-3">
                <div class="flex-grow border-t border-gray-200"></div>
                <span class="flex-shrink mx-3 text-gray-400">或选择Emoji头像</span>
                <div class="flex-grow border-t border-gray-200"></div>
              </div>
              
              <!-- Emoji头像选择器 -->
              <EmojiAvatarPicker @select="onEmojiSelected" />
            </div>

            <!-- 个人信息表单 -->
            <div class="grid grid-cols-1 gap-4">
              <div>
                <label for="username" class="block text-sm font-medium text-gray-700">用户名</label>
                <input 
                  id="username" 
                  v-model="formData.username" 
                  type="text" 
                  class="form-input mt-1 w-full rounded-md border-gray-300" 
                  placeholder="您的用户名"
                />
              </div>
              <div>
                <label for="email" class="block text-sm font-medium text-gray-700">邮箱</label>
                <input 
                  id="email" 
                  v-model="formData.email" 
                  type="email" 
                  class="form-input mt-1 w-full rounded-md border-gray-300" 
                  placeholder="您的邮箱"
                />
              </div>
              <div>
                <label for="bio" class="block text-sm font-medium text-gray-700">个人简介</label>
                <textarea 
                  id="bio" 
                  v-model="formData.bio" 
                  rows="3" 
                  class="form-textarea mt-1 w-full rounded-md border-gray-300" 
                  placeholder="介绍一下自己..."
                ></textarea>
              </div>
              <div>
                <label for="location" class="block text-sm font-medium text-gray-700">位置</label>
                <input 
                  id="location" 
                  v-model="formData.location" 
                  type="text" 
                  class="form-input mt-1 w-full rounded-md border-gray-300" 
                  placeholder="您所在的城市"
                />
              </div>
              <div>
                <label for="birthday" class="block text-sm font-medium text-gray-700">生日</label>
                <input 
                  id="birthday" 
                  v-model="formData.birthday" 
                  type="date" 
                  class="form-input mt-1 w-full rounded-md border-gray-300" 
                />
              </div>
            </div>

            <div class="pt-4 flex justify-end space-x-3">
              <button 
                type="button" 
                @click="isEditing = false; resetForm()" 
                class="py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                取消
              </button>
              <button 
                type="submit" 
                class="py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-blue-700"
                :disabled="saving"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </template>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { userApi } from '@/services/api';
import EmojiAvatarPicker from '@/components/EmojiAvatarPicker.vue';

// 获取路由参数，用于确定是查看自己的资料还是他人的资料
const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

// 资料组件状态
const loading = ref(true);
const error = ref('');
const profile = ref<any>({});
const isEditing = ref(false);
const saving = ref(false);
const formData = ref<any>({});
const fileInput = ref<HTMLInputElement | null>(null);
const previewAvatar = ref<string | null>(null);
const avatarFile = ref<File | null>(null);
const emojiAvatar = ref<string | null>(null);

// 构建完整的头像URL（查看模式）
const fullProfileAvatarUrl = computed(() => {
  if (!profile.value.avatar) return '';
  
  // 如果是完整URL，直接返回
  if (profile.value.avatar.startsWith('http')) {
    return profile.value.avatar;
  }
  
  // 如果是相对路径，添加后端基础URL
  return `http://localhost:5000${profile.value.avatar}`;
});

// 构建完整的头像URL
const fullAvatarUrl = computed(() => {
  if (!formData.value.avatar) return '';
  
  // 如果是完整URL，直接返回
  if (formData.value.avatar.startsWith('http')) {
    return formData.value.avatar;
  }
  
  // 如果是相对路径，添加后端基础URL
  return `http://localhost:5000${formData.value.avatar}`;
});

// 是否是查看自己的资料
const isOwnProfile = computed(() => {
  const userId = route.params.id;
  return !userId || userId === 'me' || userId === authStore.user?._id;
});

// 监听路由变化重新获取数据
watch(() => route.params.id, () => {
  fetchProfile();
});

// 初始化
onMounted(() => {
  fetchProfile();
});

// 启用编辑模式
function enableEditing() {
  if (isOwnProfile.value) {
    isEditing.value = true;
  }
}

// 获取个人资料
async function fetchProfile() {
  try {
    loading.value = true;
    error.value = '';
    
    if (isOwnProfile.value) {
      // 获取自己的资料
      const { data } = await userApi.getProfile();
      profile.value = data;
    } else {
      // 获取他人资料
      const userId = route.params.id as string;
      const { data } = await userApi.getUserById(userId);
      profile.value = data;
    }
    
    // 初始化表单数据
    resetForm();
  } catch (err: any) {
    error.value = err.response?.data?.message || '获取资料失败';
    console.error('获取资料失败', err);
  } finally {
    loading.value = false;
  }
}

// 更新资料
async function updateProfile() {
  console.log('开始提交表单, 头像值:', formData.value.avatar);
  
  try {
    saving.value = true;
    error.value = '';
    
    let updatedFormData = { ...formData.value };
    
    // 如果有新头像文件，先上传头像
    if (avatarFile.value) {
      console.log('上传文件头像');
      await uploadAvatar();
    } else {
      console.log('使用现有头像:', formData.value.avatar);
    }
    
    // 确保生日是ISO格式
    if (updatedFormData.birthday) {
      updatedFormData.birthday = new Date(updatedFormData.birthday).toISOString();
    }
    
    console.log('提交的完整数据:', updatedFormData);
    const { data } = await userApi.updateProfile(updatedFormData);
    
    console.log('服务器响应:', data);
    
    // 更新本地缓存的用户信息
    const user = { ...authStore.user, ...data };
    authStore.user = user;
    localStorage.setItem('user', JSON.stringify(user));
    
    // 更新个人资料和表单数据
    profile.value = data;
    resetForm();
    
    // 切换回查看模式
    isEditing.value = false;
    
    alert('个人资料更新成功！');
  } catch (err: any) {
    error.value = err.response?.data?.message || '保存资料失败';
    console.error('保存资料失败', err);
    alert('保存失败: ' + error.value);
  } finally {
    saving.value = false;
  }
}

// 选择Emoji作为头像
function onEmojiSelected(emojiValue: string): void {
  console.log('接收到Emoji选择:', emojiValue);
  
  // 清除已上传或预览的文件头像
  previewAvatar.value = null;
  avatarFile.value = null;
  
  // 设置Emoji头像到表单数据
  formData.value.avatar = emojiValue;
  console.log('设置后的表单数据:', formData.value);
}

// 上传头像
async function uploadAvatar() {
  if (!avatarFile.value) return;
  
  try {
    const formDataObj = new FormData();
    formDataObj.append('avatar', avatarFile.value);
    
    console.log('开始上传头像');
    
    const { data } = await userApi.uploadAvatar(formDataObj);
    
    console.log('头像上传成功:', data);
    
    // 更新头像地址
    profile.value.avatar = data.avatar;
    formData.value.avatar = data.avatar;
    
    // 清除预览和文件
    previewAvatar.value = null;
    avatarFile.value = null;
    
    return data.avatar;
  } catch (err: any) {
    console.error('头像上传失败:', err);
    error.value = err.response?.data?.message || '头像上传失败';
    throw err;
  }
}

// 触发文件输入
function triggerFileInput() {
  if (fileInput.value) {
    fileInput.value.click();
  }
}

// 处理文件选择
function handleFileChange(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    avatarFile.value = file;
    
    // 预览头像
    const reader = new FileReader();
    reader.onload = (e) => {
      previewAvatar.value = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
}

// 重置表单数据
function resetForm() {
  formData.value = { ...profile.value };
  
  // 格式化生日为YYYY-MM-DD
  if (formData.value.birthday) {
    const date = new Date(formData.value.birthday);
    formData.value.birthday = date.toISOString().split('T')[0];
  }
  
  previewAvatar.value = null;
  avatarFile.value = null;
}

// 格式化日期
function formatDate(dateString: string) {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
}

  // 清除头像
function clearAvatar() {
  previewAvatar.value = null;
  avatarFile.value = null;
  formData.value.avatar = '';
}
</script> 